const Router = require("koa-router");
const fs = require("fs");
const path = require("path");
const main = require("../models");
const router = new Router();
router.post("/doForm", async ctx => {
    console.log(ctx.request.body);
    var { name, age, like } = ctx.request.body;
    age = Number(age);
    console.log(ctx.request.files.logo.path)
    var filename = ctx.request.files.logo.path;
    var reader = fs.createReadStream(filename);
    var uploadFile = `./static/${path.basename(filename)}`;
    var writer = fs.createWriteStream(uploadFile);
    reader.pipe(writer)
    var logo = ctx.origin + "/" + path.basename(filename);
    var obj = {
        name,
        age,
        like,
        logo
    }
    var table = await main('home');
    var res = await table.find({ name: obj.name }).toArray();
    if (res.length) {
        ctx.body = "你的室友已经在数据库中了"
    } else {
        await table.insertOne(obj);
        await ctx.redirect("/home")
    }

})
module.exports = router;